package cn.jantd.modules.demo.sso.controller;


import cn.jantd.core.annotation.AutoLog;
import cn.jantd.core.api.vo.Result;
import cn.jantd.core.constant.CommonConstant;
import cn.jantd.core.system.query.QueryGenerator;
import cn.jantd.core.util.oConvertUtils;
import cn.jantd.modules.demo.sso.entity.SysSso;
import cn.jantd.modules.demo.sso.service.ISysSsoService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.jantd.core.util.RedisUtil;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @Author xiagf
 * @date 2019-07-04
 */
@Slf4j
@RestController
@RequestMapping("/test/sso")
public class SysSsoController {

    @Autowired
    private ISysSsoService sysUserService;
    @Autowired
    private RedisUtil redisUtil;
    /**
     * 分页列表查询
     *
     * @param user
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "用户管理-分页列表查询")
    @ApiOperation(value = "用户管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<SysSso>> queryPageList(SysSso user, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<SysSso>> result = new Result<>();
        QueryWrapper<SysSso> queryWrapper = QueryGenerator.initQueryWrapper(user, req.getParameterMap());
        Page<SysSso> page = new Page<>(pageNo, pageSize);
        IPage<SysSso> pageList = sysUserService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param jsonObject
     * @return
     */
    @AutoLog(value = "用户管理-添加")
    @ApiOperation(value = "用户管理-添加")
    @PostMapping(value = "/add")
    public Result<SysSso> add(@RequestBody JSONObject jsonObject) {
        Result<SysSso> result = new Result<>();
        System.out.println(jsonObject.toJSONString());
        try {
            SysSso user = JSON.parseObject(jsonObject.toJSONString(), SysSso.class);
            // 设置创建时间
            user.setCreateTime(new Date());
            sysUserService.addUser(user);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param jsonObject
     * @return
     */

    @AutoLog(value = "用户管理-编辑")
    @ApiOperation(value = "用户管理-编辑")
    @PutMapping(value = "/edit")
    public Result<SysSso> edit(@RequestBody JSONObject jsonObject) {
        Result<SysSso> result = new Result<>();
        try {
            SysSso sysUser = sysUserService.getById(jsonObject.getString("id"));
            if (sysUser == null) {
                result.error500("未找到对应实体");
            } else {
                SysSso user = JSON.parseObject(jsonObject.toJSONString(), SysSso.class);
                user.setUpdateTime(new Date());
                sysUserService.editUser(user);
                result.success("修改成功!");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "用户管理-通过id删除")
    @ApiOperation(value = "用户管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<SysSso> delete(@RequestParam(name = "id", required = true) String id) {
        Result<SysSso> result = new Result<>();
        // 定义SysUserDepart实体类的数据库查询LambdaQueryWrapper
        SysSso sysUser = sysUserService.getById(id);
        if (sysUser == null) {
            result.error500("未找到对应实体");
        } else {
            // 当某个用户被删除时,删除其ID下对应的部门数据
            boolean ok = sysUserService.removeById(id);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }

    /**
     * 批量删除用户
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "用户管理-批量删除用户")
    @ApiOperation(value = "用户管理-批量删除用户")
    @DeleteMapping(value = "/deleteBatch")
    public Result<SysSso> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        // 定义SysUserDepart实体类的数据库查询对象LambdaQueryWrapper

        String[] idArry = ids.split(",");
        Result<SysSso> result = new Result<>();
        if (StringUtils.isEmpty(ids)) {
            result.error500("参数不识别！");
        } else {
            this.sysUserService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "用户管理-通过id查询")
    @ApiOperation(value = "用户管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<SysSso> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<SysSso> result = new Result<>();
        SysSso sysUser = sysUserService.getById(id);
        if (sysUser == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(sysUser);
            result.setSuccess(true);
        }
        return result;
    }
    /**
     * 校验用户账号是否唯一<br>
     * 可以校验其他 需要检验什么就传什么。。。
     *
     * @param sysUser
     * @return
     */
    @ApiOperation(value = "用户管理-校验用户账号是否唯一")
    @GetMapping(value = "/checkOnlyUser")
    public Result<Boolean> checkUsername(SysSso sysUser) {
        Result<Boolean> result = new Result<>();
        // 如果此参数为false则程序发生异常
        result.setResult(true);
        String id = sysUser.getId();
        log.info("--验证用户信息是否唯一---id:" + id);
        try {
            SysSso oldUser = null;
            if (oConvertUtils.isNotEmpty(id)) {
                oldUser = sysUserService.getById(id);
            } else {
                sysUser.setId(null);
            }
            //通过传入信息查询新的用户信息
            SysSso newUser = sysUserService.getOne(new QueryWrapper<>(sysUser));
            if (newUser != null) {
                //如果根据传入信息查询到用户了，那么就需要做校验了。
                if (oldUser == null) {
                    //oldUser为空=>新增模式=>只要用户信息存在则返回false
                    result.setSuccess(false);
                    result.setMessage("用户账号已存在");
                    return result;
                } else if (!id.equals(newUser.getId())) {
                    //否则=>编辑模式=>判断两者ID是否一致-
                    result.setSuccess(false);
                    result.setMessage("用户账号已存在");
                    return result;
                }
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setResult(false);
            result.setMessage(e.getMessage());
            return result;
        }
        result.setSuccess(true);
        return result;
    }

    /**
     * 生成在添加用户情况下没有主键的问题,返回给前端,根据该id绑定部门数据
     *
     * @return
     */
    @ApiOperation(value = "用户管理-生成在添加用户情况下没有主键的问题,返回给前端,根据该id绑定部门数据")
    @GetMapping(value = "/generateUserId")
    public Result<String> generateUserId() {
        Result<String> result = new Result<>();
        log.info("我执行了,生成用户ID==============================");
        String userId = UUID.randomUUID().toString().replace("-", "");
        result.setSuccess(true);
        result.setResult(userId);
        return result;
    }
    /**
     * 生成在添加用户情况下没有主键的问题,返回给前端,根据该id绑定部门数据
     *
     * @return
     */
    @ApiOperation(value = "根据传过来的token，判断是否是正确的token")
    @GetMapping(value = "/token")
    public Result<?> tokenIsTrue(@RequestParam(name = "token", required = true) String token) {
        Result<?> result = new Result<>();
        if(redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + token)!=null){
            result.setSuccess(true);
            result.setMessage("token正确，请放行");
        }else {
            result.setSuccess(false);
            result.setMessage("token错误，请拒绝访问");
        }
        return result;
    }

}
